package com.innovation.chengzhangriji.ui.widget;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.ui.model.UINote;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;

public class MenuView extends LinearLayout implements View.OnClickListener, NoteAdapter.OnClickNoteListener {

    private static final int COL = 4;

    public interface OnClickMenuListener {
        void onClickClose();

        void onClickEditUserInfo();

        void onClickMessages();

        void onClickSettings();

        void onClickConnectDevice();

        void onClickNote(int position);

        void onLongClickNote(int position);
    }

    private OnClickMenuListener mOnClickMenuListener;

    private DisplayImageOptions options;

    private RoundedImageView imageHead;

    private CuteTextView mTextName;

    private RecyclerView mRecyclerView;

    private ImageView mImagePoint;

    private LinearLayoutManager mLinearLayoutManager;

    private NoteAdapter mNoteAdapter;

    private int mPage;

    private int mPosition;

    private boolean oneClose = true;

    private CuteImageView mButtonLeft;

    private CuteImageView mButtonRight;

    private ArrayList<UINote> mNoteList;

    private boolean isLastEmpty;

    public MenuView(Context context) {
        super(context);
        init();
    }

    public MenuView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MenuView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_close:
                if (mOnClickMenuListener == null) {
                    return;
                }
                mOnClickMenuListener.onClickClose();
                break;
            case R.id.image_head:
                mOnClickMenuListener.onClickEditUserInfo();
                break;
            case R.id.button_left:
                mPage--;
                setNotes(mPage);
                break;
            case R.id.button_right:
                mPage++;
                setNotes(mPage);
                break;
            case R.id.layout_message:
                if (mOnClickMenuListener == null) {
                    return;
                }
                mOnClickMenuListener.onClickMessages();
                break;
            case R.id.layout_settings:
                if (mOnClickMenuListener == null) {
                    return;
                }
                mOnClickMenuListener.onClickSettings();
                break;
            case R.id.layout_connect_device:
                if (mOnClickMenuListener == null) {
                    return;
                }
                mOnClickMenuListener.onClickConnectDevice();
                break;
        }
    }

    @Override
    public void onClickNote(int position) {
        if (mOnClickMenuListener != null) {
            if (isLastEmpty) {
                mNoteAdapter.setNoteOpen(position);
                mNoteAdapter.notifyDataSetChanged();
                mPosition = position + mPage * COL;
                mOnClickMenuListener.onClickNote(mPosition);
                isLastEmpty = false;
            } else {
                if (mPosition != position + mPage * COL) {
                    mNoteAdapter.setNoteOpen(position);
                    mNoteAdapter.notifyDataSetChanged();
                    mPosition = position + mPage * COL;
                    mOnClickMenuListener.onClickNote(mPosition);
                } else {
                    if (oneClose) {
                        oneClose = false;
                        mNoteAdapter.setNoteOpen(position);
                        mNoteAdapter.notifyDataSetChanged();
                        mPosition = position + mPage * COL;
                        mOnClickMenuListener.onClickNote(mPosition);
                    }
                }
            }
        }
    }

    @Override
    public void onLongClickNote(int position) {
        if (mOnClickMenuListener != null) {
            mOnClickMenuListener.onLongClickNote(position + mPage * COL);
        }
    }

    public void setOnClickMenuListener(OnClickMenuListener onClickMenuListener) {
        mOnClickMenuListener = onClickMenuListener;
    }

    public void setHeadUrl(String url) {
        ImageLoader.getInstance().displayImage(url, imageHead, options);
    }

    public void setName(CharSequence name) {
        mTextName.setText(name);
    }

    public void cleanNotes() {
        mNoteList.clear();
        mNoteAdapter.setNotes(null);
        mNoteAdapter.notifyDataSetChanged();
    }

    /**
     * 设置日记本数组
     *
     * @param notes 日记本数组
     */
    public void setNotes(Baby[] notes) {
        mNoteList.clear();
        if (notes == null || notes.length == 0) {
            isLastEmpty = true;
            return;
        }
        for (Baby baby : notes) {
            UINote note = new UINote();
            note.setBabyID(baby.getBabyID());
            note.setImageUrl(baby.getImageUrl());
            note.setName(baby.getName());
            mNoteList.add(note);
        }
        setNotes(mPage);
    }

    public void setHead(String url, String name) {
        mNoteList.get(mPosition).setImageUrl(url);
        mNoteList.get(mPosition).setName(name);
        setNotes(mPage);
        mNoteAdapter.notifyItemChanged(mPosition - (mPage * COL));
    }

    public void setPosition(int index) {
        if (index == -1) {
            mPage = 0;
            mPosition = 0;
            oneClose = true;
        } else {
            mPage = index / COL;
            mPosition = index;
            oneClose = false;
        }
    }

    public void setVisibilityPoint(int visibility) {
        mImagePoint.setVisibility(visibility);
    }

    private void init() {
        setOrientation(VERTICAL);
        setBackgroundColor(Color.WHITE);
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.layout_menu, this);
        CuteImageView buttonClose = (CuteImageView) findViewById(R.id.button_close);
        imageHead = (RoundedImageView) findViewById(R.id.image_head);
        imageHead.setOnClickListener(this);
        mTextName = (CuteTextView) findViewById(R.id.text_name);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        LinearLayout layoutMessage = (LinearLayout) findViewById(R.id.layout_message);
        LinearLayout layoutSettings = (LinearLayout) findViewById(R.id.layout_settings);
        LinearLayout layoutDevice = (LinearLayout) findViewById(R.id.layout_connect_device);
        mImagePoint = (ImageView) findViewById(R.id.image_point);
        mLinearLayoutManager = new LinearLayoutManager(getContext());
        mLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mNoteAdapter = new NoteAdapter(getContext());
        mRecyclerView.setAdapter(mNoteAdapter);
        mRecyclerView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        mButtonLeft = (CuteImageView) findViewById(R.id.button_left);
        mButtonRight = (CuteImageView) findViewById(R.id.button_right);

        buttonClose.setOnClickListener(this);
        mButtonLeft.setOnClickListener(this);
        mButtonRight.setOnClickListener(this);
        layoutMessage.setOnClickListener(this);
        layoutSettings.setOnClickListener(this);
        layoutDevice.setOnClickListener(this);
        mNoteAdapter.setOnClickNoteListener(this);
        mNoteList = new ArrayList<UINote>();

        setOptions();
        setClickable(true);
    }

    public void setNotes(int page) {
        UINote[] notes;
        int length = mNoteList.size();
        if (length == 0) {
            return;
        }

        if (page < 0) {
            mPage = 0;
        }

        if (page > length / COL) {
            mPage = length / COL;
        }
        page = mPage;

        if ((page + 1) * COL <= length) {
            notes = new UINote[COL];
        } else {
            notes = new UINote[length % COL];
        }

        for (int i = 0; i < notes.length; i++) {
            notes[i] = new UINote();
            notes[i].setBabyID(mNoteList.get(i + page * COL).getBabyID());
            notes[i].setName(mNoteList.get(i + page * COL).getName());
            notes[i].setImageUrl(mNoteList.get(i + page * COL).getImageUrl());
            notes[i].setOpen(false);
        }
        if (mPosition / COL == mPage && !isLastEmpty && !oneClose) {
            notes[mPosition % COL].setOpen(true);
        }
        mNoteAdapter.setNotes(notes);
        mNoteAdapter.notifyDataSetChanged();

        // 控制按钮
        if (length + 1 > COL) {
            mButtonLeft.setVisibility(View.VISIBLE);
            mButtonRight.setVisibility(View.VISIBLE);
        }
        if (mPage == 0) {
            mButtonLeft.setVisibility(View.INVISIBLE);
        }
        if (mPage == length / COL) {
            mButtonRight.setVisibility(View.INVISIBLE);
        }
    }

    private void setOptions() {
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_head_circle_default_small)    //在ImageView加载过程中显示图片
                .showImageForEmptyUri(R.drawable.ic_head_circle_default_small)  //image连接地址为空时
                .showImageOnFail(R.drawable.ic_head_circle_default_small)  //image加载失败
                .cacheOnDisk(true)   //加载图片时会在磁盘中加载缓存
                .build();
    }
}
